import socket
import os
import json
import struct
FILE_PATH = os.path.join(os.path.dirname(__file__), 'demo.mp4')


def socket_client():

    client = socket.socket()

    client.connect(('127.0.0.1',8848))

    #  1.制作字典形式的报头
    head_dic = {
        'MD5': 123244546656,
        'file_name':os.path.basename(FILE_PATH),
        'file_size': os.path.getsize(FILE_PATH),
        'new_file_name': 'demo1.mp4',
    }

    # 2. 获取json形式的报头
    head_dic_json = json.dumps(head_dic)

    # 3. 获取bytes形式的报头
    head_dic_json_bytes = head_dic_json.encode('utf-8')

    # 4. 获取bytes报头的总字节数
    head_len = len(head_dic_json_bytes)

    # 5. 将bytes报头的总字节数转化成固定4个字节
    four_bytes = struct.pack('i',head_len)

    # 6. 发送固定的4个字节
    client.send(four_bytes)

    # 7.发送报头
    client.send(head_dic_json_bytes)

    # 8. 发送总数据
    '''
    循环条件设定: 
        1. 根据总子节数: file_size: 493701, 每次循环1024个,
        2. 每次取数据不为空,即可.
    '''
    with open(FILE_PATH,mode='rb') as f1:
        while 1:
            every_data = f1.read(1024)
            if every_data:
                client.send(every_data)
            else:
                break

    client.close()


socket_client()







